package com.example.gulimallauthserver.controller;

import com.alibaba.fastjson.JSON;
import com.example.common.constant.AuthServerConstant;
import com.example.common.utils.R;
import com.example.common.vo.MemberVo;
import com.example.gulimallauthserver.feign.MemberFeignService;
import com.example.gulimallauthserver.feign.ThirdPartFeignService;
import com.example.gulimallauthserver.util.GiteeUtil;
import com.example.gulimallauthserver.util.HttpUtils;
import com.example.gulimallauthserver.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.example.gulimallauthserver.util.GiteeUtil.ClientID;
import static com.example.gulimallauthserver.util.GiteeUtil.RedirectUri;

@Controller
public class LoginController {
    @Autowired
    ThirdPartFeignService thirdPartFeignService;
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone){
        //接口防刷
        //验证码再次校验（redis存储）
        //只能发数字验证码
        int randomNum = ThreadLocalRandom.current().nextInt(1000, 10000);
        String code = String.valueOf(randomNum);;
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code,2, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone,code);
        return R.ok();
    }

    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        if(result.hasErrors()){
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            //model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //注册成功，回到网站首页
        //校验验证码是否正确
        String code = vo.getCode();
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(redisCode)){
            if(code.equals(redisCode)){
                //删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证码通过，调用远程服务进行注册
                R r = memberFeignService.regist(vo);
                if(r.get("code").equals(0)){
                    return "redirect:http://auth.gulimall.com/login.html";
                }else{
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }else{
                Map<String,String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            //验证码为空或者验证码错误
            Map<String,String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser == null){
            return "login";
        }else{
            return "redirect:http://gulimall.com";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo,HttpSession session){
        R r = memberFeignService.login(vo);
        if(r.get("code").equals(0)){
            MemberVo loginUser = JSON.parseObject((String) r.get("login"), MemberVo.class);
            session.setAttribute("loginUser",loginUser);
            return "redirect:http://gulimall.com";
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
    @GetMapping("/gitee/login")
    public String giteeLogin() throws UnsupportedEncodingException {
        //System.out.println("转跳成功");
        return "redirect:"+ GiteeUtil.getUrl();
    }

    @GetMapping("/gitee/auth")
    public String giteeAuth(@RequestParam("code") String code, HttpSession session) throws Exception {
        GiteeToken giteeToken = GiteeUtil.getToken(code);
        String token = giteeToken.getAccessToken();
        System.out.println("giteeToken.toString() = " + giteeToken.toString());
        if(giteeToken.getError() !=null){
            //注册失败
            return "redirect:http://auth.aulimall.com/login.html";
        }else{
            //注册成功
            GiteeUserVo userVo = GiteeUtil.getInfo(token);
            //如果当前用户第一次注册，自动注册新用户;否则查出会员信息，返回
            R r = memberFeignService.oauthlogin(userVo);
            if(r.get("code").equals(0)){
                //提取登录状态,redis存储用户登录信息
                MemberVo giteeUser = JSON.parseObject((String) r.get("gitee"), MemberVo.class);
                session.setAttribute("loginUser",giteeUser);
                return "redirect:http://gulimall.com";
            }else{
                return "redirect:http://auth.aulimall.com/login.html";
            }
        }
    }

}
